const express = require("express");
const joi = require("joi");
// 导入配置文件
const config = require('./config')


const app = express();
// 响应数据的中间件
app.use(function (req, res, next) {
    // status = 0 为成功； status = 1 为失败； 默认将 status 的值设置为 1，方便处理失败的情况
    res.cc = function (err, status = 1) {
        res.send({
            // 状态
            status,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: err instanceof Error ? err.message : err,
        })
    }
    next()
})

const expressSwagger = require('express-swagger-generator')(app);
let options = {
    swaggerDefinition: {
        info: {
            description: 'This is a sample server',
            title: 'Swagger',
            version: '1.0.0',
        },
        host: 'localhost:7111',
        basePath: '/',
        produces: [
            "application/json",
            "application/xml"
        ],
        schemes: ['http', 'https'],
        securityDefinitions: {
            JWT: {
                type: 'apiKey',
                in: 'header',
                name: 'Authorization',
                description: "",
            }
        }
    },
    route: {
        url: '/swagger',
        docs: '/swagger.json' //swagger文件 api
    },
    basedir: __dirname, //app absolute path
    files: ['./router_handler/*.js'] //Path to the API handle folder
};
expressSwagger(options)

const cors = require("cors");
app.use(cors());
app.use(express.urlencoded({ extended: false }))
app.use(express.json());

// 托管静态资源文件
app.use(express.static('./public'))



// 解析 token 的中间件
const expressJWT = require('express-jwt')
// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/user\//] }))



const userRouter = require("./router/login");
app.use('/user', userRouter);

const userInfoRouter = require("./router/userInfo");
app.use('/userInfo', userInfoRouter);

const settingRouter = require("./router/setting");
app.use('/setting', settingRouter);

const productRouter = require("./router/product");
app.use('/pro', productRouter);

const messageRouter = require("./router/message");
app.use('/msg', messageRouter);

const filesRouter = require("./router/files");
app.use('/contract', filesRouter);

const logRouter = require("./router/log");
app.use('/log', logRouter);

const overviewRouter = require("./router/overview");
app.use('/ov', overviewRouter);
// 错误中间件
app.use(function (err, req, res, next) {
    // 捕获身份认证失败的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(err)
    // 未知错误
    return res.cc(err)
})

app.listen(7111, () => {
    console.log('127.0.0.1:7111');
})